package com.primus.server.utils;

import org.apache.commons.lang3.StringUtils;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * 日期工具类
 * @author Berg
 */
public class DateUtils {

//    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

    public static String formatDate(Date date) {

        if (date == null) {
            return StringUtils.EMPTY;
        }
        return dateFormat().format(date);
    }

    public static String formatDatetime(Date date) {

        if (date == null) {
            return StringUtils.EMPTY;
        }
        return datetimeFormat().format(date);
    }

    public static Date parse(String dateInString) throws ParseException {
        if (StringUtils.isBlank(dateInString)) {
            return null;
        }
        return dateFormat().parse(dateInString);
    }

    public static Date convertFromXMLGregorianCalendar(XMLGregorianCalendar xmlGregorianCalendar) {
        LocalDateTime localDateTime = LocalDateTime.of(xmlGregorianCalendar.getYear(),
                xmlGregorianCalendar.getMonth(),
                xmlGregorianCalendar.getDay(),
                xmlGregorianCalendar.getHour(),
                xmlGregorianCalendar.getMinute(),
                xmlGregorianCalendar.getSecond());
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static XMLGregorianCalendar convertToXMlGregorianCalendar(Date date) throws DatatypeConfigurationException {
        GregorianCalendar gregory = new GregorianCalendar();
        gregory.setTime(date);
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregory);
    }

    private static SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("yyyy/MM/dd");
    }

    private static SimpleDateFormat datetimeFormat() {
        return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }
}
